<template>
  <div v-if="isLoading" class="text-center">
    <a-spin class="mt-8"/>
  </div>
  <a-result v-if="error != null" :status="500" sub-title="请尝试点击按钮刷新页面 ~" title="加载失败 ~">
    <template #extra>
      <a-button @click="refreshPage">刷新页面</a-button>
    </template>
  </a-result>
  <a-layout v-if="isFinished && error == null">
    <a-layout-sider>
      <a-menu v-model:selectedKeys="selectedKeys" :open-keys="openKeys" mode="inline" theme="dark"
              @select="handleMenuSelect">
        <template v-for="menu in menus">
          <a-sub-menu v-if="menu.subMenus != null && menu.subMenus.length > 1 || menu.showSinglePage" :key="menu.key">
            <template #icon>
              <line-chart-outlined v-if="menu.icon === 'line-chart'"/>
              <user-outlined v-else-if="menu.icon === 'user'"/>
              <setting-outlined v-else-if="menu.icon === 'setting'"/>
              <pay-circle-outlined v-else-if="menu.icon === 'pay'"/>
              <ordered-list-outlined v-else-if="menu.icon === 'ordered'"/>
              <team-outlined v-else-if="menu.icon === 'team'"/>
              <appstore-outlined v-else-if="menu.icon === 'app'"/>
              <account-book-outlined v-else-if="menu.icon === 'account'"/>
              <node-expand-outlined v-else-if="menu.icon === 'node'"/>
              <notification-outlined v-else-if="menu.icon === 'notification'"/>
              <profile-filled v-else-if="menu.icon === 'profile'"/>
              <play-square-filled v-else-if="menu.icon === 'play-square'"/>
              <read-filled v-else-if="menu.icon === 'read'"/>
              <cloud-filled v-else-if="menu.icon === 'cloud'"/>
              <signal-filled v-else-if="menu.icon === 'signal'"/>
              <alert-filled v-else-if="menu.icon === 'alert'"/>
              <sound-filled v-else-if="menu.icon === 'sound'"/>
              <layout-filled v-else-if="menu.icon === 'layout'"/>
              <fund-projection-screen-outlined v-else-if="menu.icon === 'fund-projection-screen'"/>
            </template>
            <template #title>
              <span>{{ menu.text }}</span>
            </template>
            <a-menu-item v-for="subMenu in menu.subMenus" :key="subMenu.key">
              <template #icon>
                <home-outlined v-if="subMenu.icon === 'home'"/>
                <user-outlined v-else-if="subMenu.icon === 'user'"/>
                <setting-outlined v-else-if="subMenu.icon === 'setting'"/>
                <pay-circle-outlined v-else-if="subMenu.icon === 'pay'"/>
              </template>
              {{ subMenu.text }}
            </a-menu-item>
          </a-sub-menu>
          <a-menu-item v-else-if="menu.subMenus != null && menu.subMenus.length === 1 && !menu.showSinglePage"
                       :key="menu.subMenus[0].key">
            <template #icon>
              <home-outlined v-if="menu.icon === 'home'"/>
              <user-outlined v-else-if="menu.icon === 'user'"/>
              <line-chart-outlined v-else-if="menu.icon === 'line-chart'"/>
              <setting-outlined v-else-if="menu.icon === 'setting'"/>
              <profile-filled v-else-if="menu.icon === 'profile'"/>
              <play-square-filled v-else-if="menu.icon === 'play-square'"/>
              <read-filled v-else-if="menu.icon === 'read'"/>
              <cloud-filled v-else-if="menu.icon === 'cloud'"/>
              <signal-filled v-else-if="menu.icon === 'signal'"/>
              <alert-filled v-else-if="menu.icon === 'alert'"/>
              <sound-filled v-else-if="menu.icon === 'sound'"/>
              <layout-filled v-else-if="menu.icon === 'layout'"/>
              <fund-projection-screen-outlined v-else-if="menu.icon === 'fund-projection-screen'"/>
            </template>
            {{ menu.text }}
          </a-menu-item>
        </template>
      </a-menu>
    </a-layout-sider>

    <a-layout>
      <a-layout-header class="flex justify-between items-center" style="background: #fff; padding: 0">
        <h1>{{ title }}</h1>

        <a-dropdown>
          <a class="profile">
            <a-avatar class="avatar">
              <user-outlined/>
            </a-avatar>
            <div class="username">{{ data?.name }}</div>
          </a>
          <template #overlay>
            <a-menu @click="handleUserMenuClick">
              <change-password/>
              <a-menu-divider/>
              <a-menu-item key="logout">
                <logout-outlined/>
                退出登录
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>

      </a-layout-header>
      <a-layout-content>
        <div class="breadcrumb">
          <a-breadcrumb>

          </a-breadcrumb>
        </div>
        <div class="content">
          <router-view/>
        </div>
      </a-layout-content>
    </a-layout>

  </a-layout>
</template>
<script setup>
import config from "../config";
import pages from "../pages";
import {
  AccountBookOutlined,
  AlertFilled,
  AppstoreOutlined,
  CloudFilled,
  FundProjectionScreenOutlined,
  HomeOutlined,
  LayoutFilled,
  LineChartOutlined,
  LogoutOutlined,
  NodeExpandOutlined,
  NotificationOutlined,
  OrderedListOutlined,
  PayCircleOutlined,
  PlaySquareFilled,
  ProfileFilled,
  ReadFilled,
  SettingOutlined,
  SignalFilled,
  SoundFilled,
  TeamOutlined,
  UserOutlined
} from "@ant-design/icons-vue";
import {allowed, clearProfile, setProfile} from "../profile";
import ChangePassword from "./system/components/change-password.vue";

const refreshPage = () => {
  window.location.reload();
}

// 登录检测
const {data, isFinished, isLoading, error} = useApi({
  url: '/profile'
});
watchEffect(() => {
  if (isFinished.value) {
    setProfile(data.value);
  }
});

const currentRoute = useRoute();

const pageIndex = pages.reduce((index, page) => {
  index[page.key] = page;
  return index;
}, {});

const menus = computed(() => {
  if (data.value == null) {
    return [];
  }
  return config.menus.map(menu => {
    if (menu.pages == null) {
      return {
        key: menu.key || menu.path,
        text: menu.text,
        icon: menu.icon
      };
    }
    return {
      key: menu.key || menu.path,
      defaultOpen: menu.defaultOpen,
      showSinglePage: menu.showSinglePage,
      text: menu.text,
      icon: menu.icon,
      subMenus: menu.pages.map(key => {
        const page = pageIndex[key];
        if (page == null) {
          console.error(`页面不存在：${key}`);
          return null;
        }
        if (!allowed(page.permission)) {
          return null;
        }
        return {
          key: page.key,
          text: page.title,
          icon: page.icon,
          path: page.path
        };
      }).filter(Boolean)
    };
  }, []).filter(menu => menu.subMenus == null || menu.subMenus.length > 0);
});

const selectedKeys = ref([]);
watchEffect(() => {
  if (currentRoute.path != null) {
    selectedKeys.value = [currentRoute.path];
  }
});

const openKeys = computed(() => {
  return menus.value.filter(
    menu => menu.defaultOpen || (menu.subMenus && menu.subMenus.some(subMenu => subMenu.key === currentRoute.path))
  ).map(menu => menu.key)
});
const title = computed(() => currentRoute.meta.title);

const router = useRouter();
const handleMenuSelect = async (item) => {
  await router.push({
    path: item.key
  });
};

const {execute} = useApi({
  method: 'POST',
  url: '/logout',
  immediate: false
});
const handleUserMenuClick = async item => {
  // 退出登录
  if (item.key === 'logout') {
    const hide = message.loading('正在退出登录 ...');
    await execute();
    hide();
    clearProfile();
    await router.push('/login');
  }
}
</script>

<style lang="scss" scoped>
.ant-layout {
  min-height: 100vh;
  background: #fff;
}

.ant-layout-header {
  box-shadow: 0 0 12px rgba(#000, .15);

  h1 {
    line-height: 64px;
    margin: 0 0 0 16px;
  }

  .profile {
    display: flex;
    align-items: center;
    float: right;
    padding: 0 24px;

    .avatar {
      background: #4470F5;
    }

    .username {
      margin-left: 8px;
      color: #333;
    }

    &:hover {
      background: #f5f5f5;
      cursor: pointer;
    }
  }
}

.content {
  margin: 12px 16px;
}

.breadcrumb {
  margin: 12px 16px;
}

.trigger {
  font-size: 18px;
  height: 64px;
  display: flex;
  align-items: center;
  padding: 0 24px;
  cursor: pointer;
  transition: color 0.3s;
}

.trigger:hover {
  background: #f5f5f5;
}
</style>
